/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-15 Time: 23:16
 *
 * 新建报修工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    FlatList,
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from "./InstantMaintenanceOrderScreen.Style";
import {getIMOrderDs} from "./Actions"
import {FetchStatus} from "../../../../configuration/RequestConfiguration";
import Search from "../PersonnelStatusScreen/component/Search";

class InstantMaintenanceOrderScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: '即时维修单',
        headerRight: <Search navigation={navigation} searchCode={"depart,status"} selectValue={navigation.getParam('selectValue')} pageBack={"InstantMaintenanceOrderScreen"} dataBack={(data)=>{
            Object.assign(navigation.getParam('selectValue'), data);
            navigation.state.params.navigateDataBack();
        }}/>
    })

    //构造
    constructor(props) {
        super(props);

        this.state = {
            selectValue:{"status":"处理中"},//查询条件
            defaultMsg:[],
            showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,//当前第几页
            totalPage:0,//总的页数
            itemNo:20,//item的个数
            recordNum:0,//数据总条数
            refreshing:false,//下拉刷新
        };
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onIMOrder !== this.props.onIMOrder && nextProps.onIMOrder.fetchStatus === FetchStatus.Success) {
            let defaultInfo = nextProps.onIMOrder.rows;
            this.state.showFoot = 0;
            if(this.state.pageNo>=nextProps.onIMOrder.total){
                this.state.showFoot = 1;//listView底部显示没有更多数据了
            }
            if(this.state.pageNo===1){
                defaultInfo = nextProps.onIMOrder.rows
            }else{
                defaultInfo = this.state.defaultMsg.concat(defaultInfo)
            }
            this.setState({
                defaultMsg: defaultInfo,
                totalPage:nextProps.onIMOrder.total,
                recordNum:nextProps.onIMOrder.records,
                itemNo:20,//item的个数
                refreshing:false,
            });
        }
    }

    // 组件渲染后调用
    componentDidMount() {
        this.setState({
            pageNo:1,
        });

        this.props.navigation.setParams({navigateDataBack:this.onPressToDataBack,selectValue:this.state.selectValue});

        // this.props.navigation.navigate('MainNavigator');
        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":this.state.selectValue};

        dispatch(getIMOrderDs(JSON.stringify(str),this.state.pageNo));
    }

    onPressToDataBack=()=> {
        this.state.pageNo=1;
        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":this.state.selectValue};

        dispatch(getIMOrderDs(JSON.stringify(str),this.state.pageNo));
    };

    render(){
        return (
            <SafeAreaView style={styles.body}>

                <View style={styles.body}>
                    <View style={styles.headerContainer}>
                        <Text style={styles.headerText}>
                            共{this.state.recordNum?this.state.recordNum:'0'}张单
                        </Text>
                    </View>
                    <FlatList
                        data = {this.state.defaultMsg}
                        onRefresh = {this._onRefresh.bind(this)} //刷新操作
                        refreshing = {this.state.refreshing}
                        renderItem={this._renderItem}
                        ListFooterComponent={this._renderFooter.bind(this)}
                        onEndReachedThreshold={0.1}
                        keyExtractor={(item, index) => index.toString()}
                        onEndReached={this._onEndReached.bind(this)}
                    />
                </View>
            </SafeAreaView>
        )
    }

    //下拉刷新,更改状态，重新获取数据
    _onRefresh(){
        this.setState({
            refreshing:true,
            defaultMsg:[]
        },()=>{
            this.onPressToDataBack();
        });
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot !== 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.pageNo!==1) && (this.state.pageNo>=this.state.totalPage)){
            return;
        } else {
            this.state.pageNo++;
        }
        //底部显示正在加载更多数据
        this.state.showFoot=2;

        //获取数据
        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":this.state.selectValue};
        dispatch(getIMOrderDs(JSON.stringify(str),this.state.pageNo))
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    {/*<ActivityIndicator />*/}
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    //列表内容循环
    _renderItem = ({ item }) => {
        let _this=this;
        return (
            <TouchableOpacity activeOpacity={0.8}  onPress={() => {
                this.props.navigation.navigate('DepartmentalRepairOrderDetailScreen',{"sn":item.sn,"beforePage":"DepartmentalRepairOrderScreen",callBack:()=>{
                        let {dispatch} = _this.props;
                        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":_this.state.selectValue};
                        dispatch(getIMOrderDs(JSON.stringify(str),_this.state.pageNo))
                    }})
            }}>
                <View style={styles.boxBody} onPress={()=>{

                }}>
                    <View style={styles.top}>
                        <View style={styles.topLeft}>
                            <Text style={styles.topPointText}>
                                {item.object_fullname ? (item.object_fullname.length > 10 ? item.object_fullname.substr(0, 10) + "..." : item.object_fullname) : ""}
                            </Text>
                        </View>
                        <View style={styles.topRight}>
                            {item.type==="紧急维修"?<Text style={styles.topFromTextRed}>{item.type}</Text>:<Text style={styles.topFromTextBlue}>{item.type}</Text>}
                        </View>
                    </View>

                    <View style={styles.center}>
                        <Text style={styles.centerText}>
                            {item.area_fullname ? (item.area_fullname.length > 17 ? item.area_fullname.substr(0, 17) + "..." : item.area_fullname) : ""}
                        </Text>
                    </View>

                    <View style={[styles.center,{marginTop:1}]}>
                        <Text style={styles.centerText}>
                            {item.remark ? (item.remark.length > 100 ? item.remark.substr(0, 100) + "..." : item.remark) : ""}
                        </Text>
                    </View>

                    <View style={styles.bottom}>
                        <Text style={styles.bottomText}>
                            {item.create_datetime}
                        </Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

}

const props = state => {
    return {
        onIMOrder: state.onIMOrder,
    }
};

export default InstantMaintenanceOrderScreen = connect(props)(InstantMaintenanceOrderScreen);
